package com.qf.servelt;


import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.UserServiceImpl;

import com.qf.utils.StrUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;


@WebServlet("/user")
public class UserController extends BaseServlet{
    public String login(HttpServletRequest request, HttpServletResponse response) {
//      获取用户参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
//      判断用户名   密码  验证码 不为空   如果为空重定向到登录页面
        if(!StrUtils.empty(username) ||!StrUtils.empty(password)){
            request.setAttribute("msg", "用户名，密码，不能为空");
            return "forward:/login.jsp";
        }

//      调用service完成用户名密码的校验
        UserService userService = new UserServiceImpl();
        User user = (userService).login(username, password);
//      判断用户名 密码是否错误   如果错误返回提示信息
        if(user == null){
            request.setAttribute("username", username);
            request.setAttribute("password", password);
            return "forward:/login.jsp";
        }

//        登录成功的话，将用户信息放入tomcat的session会话中携带
        request.getSession().setAttribute("loginUser", user);
        return "redirect:/list.jsp";
    }

    public String register(HttpServletRequest request,HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        Map<String, String[]> parameterMap = request.getParameterMap();

        User user =new User();
        BeanUtils.populate(user, parameterMap);
        UserService userService = new UserServiceImpl();
        int i = userService.addUser(user);
        if (i >0){
            return "forward:/login.jsp";
        }else {
            return "rdirect:/register.jsp";
        }
    }

}
